<template>
  <div class="my-create hide-scroller-bar" @scroll="loadImg($event)">
    <a-spin v-if="total > 0" :spinning="false" :delay="600">
      <div
        class="discover"
        v-masonry
        transition-duration="0.1s"
        item-selector=".discoveImg"
        id="discover-width"
        fit-width="true"
      >
        <div
          v-for="item in list"
          :key="item.id"
          class="discoveImg"
          v-masonry-tile
          :style="{
            width: imageWidth + 'px',
          }"
        >
          <template v-if="item.images && item.images.length">
            <div class="discoveTxt" @click.stop="makeTheSameModelClick(item)">
              <a-row class="bottom-text mask-right">
                <div class="icon-bg">
                  <VerticalAlignBottomOutlined
                    v-if="!item.downloadLoading"
                    @click.stop="downloadClick(item)"
                  />
                  <LoadingOutlined v-else />
                </div>
                <div class="icon-bg" @click.stop="del(item)">
                  <DeleteOutlined />
                </div>
              </a-row>
              <div class="text-box">
                {{ item.title }}
              </div>
              <div class="make-box" @click.stop="makeTheSameModelClick(item)">
                创作
              </div>
            </div>

            <img
              v-if="item.images"
              v-lazy="
                item.images[0] && item.images[0].webp
                  ? item.images[0] && item.images[0].webp
                  : item.images[0] && item.images[0].uri
              "
              :style="{
                width: imageWidth + 'px',
                height:
                  imageWidth *
                    (item.images[0] &&
                      item.images[0].height /
                        (item.images[0] && item.images[0].width)) +
                  'px',
              }"
            />
          </template>
          <template v-else>
            <div class="item-img-wrapper">
              <div class="image_item_img">{{ judgeStatus(item.status) }}</div>
              <div class="operate-image-cover" @click.stop="del(item)">
                <DeleteOutlined />
              </div>
            </div>
          </template>
        </div>
      </div>
    </a-spin>
    <div v-else class="no-data">
      <a-empty />
    </div>
    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<script>
import {
  ref,
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  onMounted,
  nextTick,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import {
  DeleteOutlined,
  VerticalAlignBottomOutlined,
  LoadingOutlined,
} from "@ant-design/icons-vue";
import defaultSetting from "../../common/utils/defaultSetting";
import _ from "lodash";
import axios from "axios";
import moment from "moment";
export default defineComponent({
  name: "Create",
  components: { DeleteOutlined, VerticalAlignBottomOutlined, LoadingOutlined },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const cateId = ref(route.params.cateId || null);
    const pluginId = ref(route.query.pluginId || null);

    const state = reactive({
      loading: false,
      loginVisible: false,
      list: [],
      page: 1,
      total: 0,
      imageWidth: 0,
      downloadLoading: true,
    });

    const getMyCreate = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        state.loading = true;
        let params = {
          title: "",
          page: state.page,
          pageSize: 20,
        };
        request
          .get("/work_ai", "/user/ai/case/list", params)
          .then((res) => {
            state.loading = false;
            console.log(res);
            if (state.page == 1) {
              state.list = res.result.data;
            } else {
              state.list = [...state.list, ...res.result.data];
            }
            state.total = res.result.total;
            if (state.total > 0) {
              nextTick(() => {
                document.getElementById("discover-width").style.marginLeft =
                  "30px";
              });
            }
          })
          .catch((err) => {
            state.loading = false;
          });
      });
    };
    onMounted(() => {
      state.imageWidth = Math.floor((document.body.clientWidth - 244 - 75) / 6);
    });
    getMyCreate();
    const loadImg = (event) => {
      let el = event.target;
      console.log(el.scrollTop, "el.scrollTop");
      console.log(el.clientHeight, "el.clientHeight");
      console.log(el.scrollHeight, "el.scrollHeight");
      if (
        Math.ceil(el.scrollTop + el.clientHeight) >= el.scrollHeight &&
        state.list.length < state.total
      ) {
        state.page++;
        getMyCreate();
      }
    };
    // 制作同款
    const makeTheSameModelClick = (item) => {
      if (!item.images.length) {
        return;
      }
      utils.setStorage("caseInfo", JSON.stringify(item));
      utils.setStorage("case_tab", 2);
      let url = `${
        utils.isEnv() ? "http://localhost:4022" : defaultSetting.requestDomain
      }`;
      let link = url + `/#/paintModel/detail?id=${item.id}`;
      window.open(link);
    };
    const del = (item) => {
      utils.modalConfirm({
        title: "提示",
        content: "确定要删除此创作吗？",
        onOk: () => {
          request
            .del("/work_ai", "/user/image/case/delete", {
              id: item.id,
            })
            .then((res) => {
              message.success("删除成功！");
              state.page = 1;
              state.list = [];
              getMyCreate();
            });
        },
      });
    };
    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };
    const downloadClick = (item) => {
      if (item.images.length > 1) {
        // // 设置请求URL和参数
        const url = "/api/work_ai/user/image/case/download";
        const params = {
          caseId: item.id,
          org_id: store.getters.orgId,
        };
        item.downloadLoading = true;
        // 发送GET请求
        axios
          .get(url, {
            params,
            responseType: "blob", // 告诉axios要响应二进制数据类型
          })
          .then((response) => {
            // 创建Blob对象
            console.log(response, "responseresponse");
            const blob = new Blob([response.data], { type: "application/zip" });
            // 创建URL对象，并模拟点击链接进行下载
            const downloadUrl = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = downloadUrl;
            link.download =
              store.getters.orgId +
              item.id +
              moment(new Date()).format("YYYYMMDD"); // 下载文件名
            link.click();
          })
          .catch((error) => {
            setTimeout(() => {
              item.downloadLoading = false;
            }, 0);
          })
          .finally(() => {
            setTimeout(() => {
              item.downloadLoading = false;
            }, 0);
          });
      } else {
        var image = new Image();
        // 解决跨域 Canvas 污染问题
        // crossorigin 是HTML5中新增的<img>标签属性
        //anonymous:如果使用这个值的话就会在请求中的header中的带上origin属性，但请求不会带上cookie和其他的一些认证信息。
        //use-credentials:这个同时会在跨域请求中带上cookie和其他的一些认证信息。在使用这两个值时都需要server端在response的header中带上Access-Control-Allow-Credentials属性。可以通过server的配置文件来开启这个属性：server开启Access-Control-Allow-Credentials
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          var url = canvas.toDataURL("image/png");
          // 生成一个a元素
          var a = document.createElement("a");
          // 创建一个单击事件
          var event = new MouseEvent("click");
          // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
          a.download = item.images[0].origin_uri.substring(
            item.images[0].origin_uri.lastIndexOf("/") + 1
          );
          // 将生成的URL设置为a.href属性
          a.href = url;

          // 触发a的单击事件
          a.dispatchEvent(event);
        };
        image.src = item.images[0].uri;
      }
    };
    // 判断作品是生成中还是生成错误
    const judgeStatus = (status) => {
      let text = "图片生成中...";
      if (status == "starting" || status == "processing" || status == "queue") {
        text = "图片生成中..."; //生成中
      } else if (
        status == "failed" ||
        status == "canceled" ||
        status == "error"
      ) {
        text = "图片生成失败"; //生成失败
      } else {
        text = ""; //成功
      }
      return text;
    };
    return {
      ...toRefs(state),
      loadImg,
      makeTheSameModelClick,
      del,
      loginCallback,
      downloadClick,
      judgeStatus,
    };
  },
});
</script>

<style lang="less" scoped>
.my-create {
  width: 100%;
  height: 100%;
  overflow: hidden auto;
}
.discover {
  margin-top: 30px;
  margin-bottom: 30px;
}
.discoveImg {
  margin-right: 15px;
  margin-bottom: 15px;
  border-radius: 15px;
  position: relative;
  // width: 16.65%;
  .discoveTxt {
    width: 90%;
    height: 95%;
    position: absolute;
    cursor: pointer;

    .bottom-text {
      position: absolute;
      right: 0;
      width: 100%;
      // padding-right: 10px;
      display: flex;
      justify-content: flex-end;
    }
    .mask-right {
      position: absolute;
      right: 10px;
      bottom: 30px;
      width: 80px;
      height: 28px;
      background: rgba(0, 0, 0, 0.1);
      border-radius: 24px;
      backdrop-filter: blur(4px);
      display: flex;
      justify-content: space-around;
      align-items: center;

      .icon-bg {
        width: 25px;
        height: 25px;
        text-align: center;
        line-height: 25px;
        // background-color: #00000073;
        opacity: 0.8;
        border-radius: 50%;
        // margin-bottom: 10px;
        color: #fff;
        font-size: 16px;
        // background-image: linear-gradient(to bottom right, #938bff, #daaefe);
      }
      display: none;
    }

    .text-box {
      width: 90%;
      color: #cbd5e1;
      position: absolute;
      bottom: 80px;
      left: 5%;
      flex-direction: column;
      background: #0f121c;
      box-shadow: 0 4px 14px 0 rgba(0, 0, 0, 0.5);
      border-radius: 8px;
      padding: 10px 12px 15px 12px;
      box-sizing: border-box;
      z-index: 2;
      display: none;
    }
    .make-box {
      color: #fff;
      padding: 8px 15px;
      position: absolute;
      top: 12px;
      right: 12px;
      background: #f1314e;
      border-radius: 50px;
      box-sizing: border-box;
      z-index: 2;
      display: none;
    }
  }

  img {
    border-radius: 12px;
    width: 100% !important;
    cursor: pointer;
    object-fit: cover;
  }
}
.discoveImg > .discoveTxt:hover {
  width: 100%;
  position: absolute;
  cursor: pointer;
  // display: block;

  .text-box {
    display: block;
    min-height: auto;
    max-height: 81px;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  .make-box {
    display: block;
  }

  .bottom-text {
    position: absolute;
    right: 0;
    width: 100%;
    // padding-right: 10px;
    display: flex;
    justify-content: flex-end;
    display: block;
  }
  .mask-right {
    position: absolute;
    right: 10px;
    bottom: 0px;
    width: 80px;
    height: 28px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 24px;
    backdrop-filter: blur(4px);
    display: flex;
    justify-content: space-around;
    align-items: center;

    .icon-bg {
      width: 25px;
      height: 25px;
      text-align: center;
      line-height: 25px;
      // background-color: #00000073;
      opacity: 0.8;
      border-radius: 50%;
      // margin-bottom: 10px;
      color: #fff;
      font-size: 16px;
      // background-image: linear-gradient(to bottom right, #938bff, #daaefe);
    }
  }
}
.item-img-wrapper {
  position: relative;
  cursor: pointer;
  &:hover .operate-image-cover {
    opacity: 1;
  }
}
.image_item_img {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 340px;
  background: linear-gradient(to top right, #a871ec, #dc7be0);

  border-radius: 5px;
  color: #fff;
}
.operate-image-cover {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 28px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 24px;
  backdrop-filter: blur(4px);
  opacity: 0;
  position: absolute;
  right: 20px;
  bottom: 20px;
  color: #fff;
}
.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
